// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

#include "padding.h"

namespace ncnn {

Padding::Padding()
{
    one_blob_only = true;
    support_inplace = false;
}

/**
 * 将参数读取存在成员变量中
 */
int Padding::load_param(const ParamDict& pd)
{
    // 读取参数
    top = pd.get(0, 0);
    bottom = pd.get(1, 0);
    left = pd.get(2, 0);
    right = pd.get(3, 0);
    type = pd.get(4, 0);
    value = pd.get(5, 0.f);
    per_channel_pad_data_size = pd.get(6, 0);
    front = pd.get(7, 0);
    behind = pd.get(8, 0);

    // 如果填充的参数都是-233/-234，则one_blob_only=false
    // todo -233和-234 是什么意思？
    // TODO one_blob_only 的意义是什么？
    if (top == -233 && bottom == -233 && left == -233 && right == -233)
    {
        one_blob_only = false;
    }
    if (top == -234 && bottom == -234 && left == -234 && right == -234)
    {
        one_blob_only = false;
    }

    return 0;
}

int Padding::load_model(const ModelBin& mb)
{
    if (per_channel_pad_data_size)
    {
        per_channel_pad_data = mb.load(per_channel_pad_data_size, 1);
    }

    return 0;
}

/**
 * 拷贝原矩阵到目标矩阵
 * 扩展矩阵边界
 * 
 * 整个函数采用的是普通的遍历指针赋值的方式，使用if来区分
 * 唯一进行优化的地方是判断了拷贝的字节数，如果小于12个字节，则采用指针复制，大于12个字节采用memcpy
 * 
 * 
 * @param src：原矩阵
 * @param dst: 已经扩展了矩阵的尺寸的目标矩阵
 * @param top: 扩展了矩阵的顶边距
 * @param left: 扩展了矩阵的左边距
 * @param type: 作用未知，估计是按照指定的type填充扩展的边界
 * @param v: 该值是用来
 */
template<typename T>
static void copy_make_border_image(const Mat& src, Mat& dst, int top, int left, int type, T v)
{
    int w = dst.w;
    int h = dst.h;

    const T* ptr = src;
    T* outptr = dst;

    if (type == 0)
    {
        /**
         * type = 0 的填充方式
         * 
         * 填充的边按照指定的值进行填充
         */
        int y = 0;
        // fill top
        for (; y < top; y++)
        {
            int x = 0;
            for (; x < w; x++)
            {
                outptr[x] = v;
            }
            outptr += w;
        }
        // fill center
        for (; y < (top + src.h); y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = v;
            }
            if (src.w < 12)
            {
                // 原矩阵宽度小于12，那么使用遍历赋值的方式
                // 猜测不使用memcpy主要是因为效率
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                // 如果原矩阵的宽度大于12，那么使用memcpy进行行复制
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                // 这里将x的值加上矩阵的尺寸
                x += src.w;
            }
            // 由于之前的步骤已经将x起始值增加了左边距和矩阵的尺寸，所以这里直接进行
            // 遍历赋值操作
            for (; x < w; x++)
            {
                outptr[x] = v;
            }
            // 原矩阵的指针进行行偏移，进入下一行
            ptr += src.w;
            // 目标矩阵的指针进行偏移，进入下一行
            outptr += w;
        }
        // fill bottom
        for (; y < h; y++)
        {
            int x = 0;
            for (; x < w; x++)
            {
                outptr[x] = v;
            }
            outptr += w;
        }
    }
   
    if (type == 1)
    {
        /**
         * 类型1填充方式：对于外部区域是将原矩阵的边界值填充到外部区域
         */
        int y = 0;
        // fill top 填充顶边
        for (; y < top; y++)
        {
            int x = 0;
            // 矩阵顶边的矩阵left top外部区域按照
            // 矩阵的坐上角的像素值填充
            for (; x < left; x++)
            {
                outptr[x] = ptr[0];
            }
            if (src.w < 12)
            {
                // 原矩阵宽度小于12，那么使用遍历赋值的方式
                // 猜测不使用memcpy主要是因为效率
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                // 使用memcpy直接进行拷贝
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                // 矩阵的顶右外部区域，按照原矩阵的右上角顶点像素值填充
                outptr[x] = ptr[src.w - 1];
            }
            // 下一行填充
            outptr += w;
        }
        // fill center
        for (; y < (top + src.h); y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = ptr[0];
            }
            if (src.w < 12)
            {
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                outptr[x] = ptr[src.w - 1];
            }
            ptr += src.w;
            outptr += w;
        }
        // fill bottom
        ptr -= src.w;
        for (; y < h; y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = ptr[0];
            }
            if (src.w < 12)
            {
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                outptr[x] = ptr[src.w - 1];
            }
            outptr += w;
        }
    }

    if (type == 2)
    {
        /**
         * 类型2的填充方式：镜像填充
         */
        int y = 0;
        // fill top 这里有一个问题，如果填充的顶边距大于原矩阵的高度会出问题
        ptr += top * src.w;
        for (; y < top; y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = ptr[left - x];
            }
            if (src.w < 12)
            {
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                outptr[x] = ptr[src.w - (x - left - src.w) - 2];
            }
            outptr += w;
            ptr -= src.w;
        }
        // fill center
        for (; y < (top + src.h); y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = ptr[left - x];
            }
            if (src.w < 12)
            {
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                outptr[x] = ptr[src.w - (x - left - src.w) - 2];
            }
            ptr += src.w;
            outptr += w;
        }
        // fill bottom
        ptr -= 2 * src.w;
        for (; y < h; y++)
        {
            int x = 0;
            for (; x < left; x++)
            {
                outptr[x] = ptr[left - x];
            }
            if (src.w < 12)
            {
                for (; x < (left + src.w); x++)
                {
                    outptr[x] = ptr[x - left];
                }
            }
            else
            {
                memcpy(outptr + left, ptr, src.w * sizeof(T));
                x += src.w;
            }
            for (; x < w; x++)
            {
                outptr[x] = ptr[src.w - (x - left - src.w) - 2];
            }
            outptr += w;
            ptr -= src.w;
        }
    }
}

int Padding::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
    // 如果填充边为0，则不进行填充，直接返回
    if (top == 0 && bottom == 0 && left == 0 && right == 0 && front == 0 && behind == 0)
    {
        top_blob = bottom_blob;
        return 0;
    }

    int w = bottom_blob.w;
    int h = bottom_blob.h;
    int channels = bottom_blob.c;
    int dims = bottom_blob.dims;
    size_t elemsize = bottom_blob.elemsize;

    // outw 填充后的矩阵宽度
    int outw = w + left + right;

    // 如果矩阵的维度只有1
    // 这里不能将矩阵视为通道，要和tensorflow中作为对比
    // 这里的1维矩阵，也就只是个数组
    if (dims == 1)
    {
        // 创建一个矩阵尺寸为outw的相同参数的矩阵
        top_blob.create(outw, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        // 根据不同的单个元素的字节数，选择不同的数据类型继续padding扩充
        // 这里利用c++模板技术，复用主要流程
        if (elemsize == 1)
            copy_make_border_image<signed char>(bottom_blob, top_blob, 0, left, type, static_cast<signed char>(value));
        if (elemsize == 2)
            copy_make_border_image<unsigned short>(bottom_blob, top_blob, 0, left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(value) : float32_to_bfloat16(value));
        if (elemsize == 4)
            copy_make_border_image<float>(bottom_blob, top_blob, 0, left, type, value);

        return 0;
    }

    // 计算矩阵的第二维扩展维度
    int outh = h + top + bottom;

    if (dims == 2)
    { 
        top_blob.create(outw, outh, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        if (elemsize == 1)
            copy_make_border_image<signed char>(bottom_blob, top_blob, top, left, type, static_cast<signed char>(value));
        if (elemsize == 2)
            copy_make_border_image<unsigned short>(bottom_blob, top_blob, top, left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(value) : float32_to_bfloat16(value));
        if (elemsize == 4)
            copy_make_border_image<float>(bottom_blob, top_blob, top, left, type, value);

        return 0;
    }

    // 计算矩阵第三维的维度
    int outc = channels + front + behind;

    if (dims == 3)
    {
        // todo: 看到这里
        top_blob.create(outw, outh, outc, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        // 三维矩阵的扩展方式和之前不一样
        // 根据以下的遍历方式可推测，三位矩阵的排列方式：(channel，width， height)
        #pragma omp parallel for num_threads(opt.num_threads)
        for (int q = 0; q < outc; q++)
        {
            // 以通道进行遍历
            Mat borderm = top_blob.channel(q);

            // 获取当前通道下扩展边界时，填充的值
            float pad_value = per_channel_pad_data_size ? per_channel_pad_data[q] : value;

            //Channel padding
            // 如果当前通道处于前或者后（范围之外），且填充方式为CONSTANT时
            if (((q < front) || (q >= (channels + front))) && type == 0)
            {
                // 根据不同的单个元素尺寸，采用不同的填充值的方式进行填充
                if (elemsize == 1)
                {
                    borderm.fill(static_cast<signed char>(pad_value));
                }
                if (elemsize == 2)
                {
                    // 针对只有2个字节的矩阵，这种矩阵一般是半精度浮点数，
                    borderm.fill(support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(pad_value) : float32_to_bfloat16(pad_value));
                }
                if (elemsize == 4)
                {
                    borderm.fill(pad_value);
                }
            }
            else
            {
                // 进入在这里，说明采用的不是常量值填充并且处于范围之内的通道进行填充
                int q_ = q - front;

                if (type == 1)
                {   
                    // 这里使用的扩展像素填充的策略是边缘延展
                    // q_ <= 0 表示当前遍历的channel处于矩阵之外，根据
                    // 边缘镜像扩展的方法，只需要定位到边缘即可获取扩展的像素
                    // 同理下面的判断也是
                    // 这里的操作是将值限定在合法的范围内
                    q_ = q_ <= 0 ? 0 : q_;
                    q_ = q_ >= channels - 1 ? channels - 1 : q_;
                }
                // 这里是否可以采用else的方式进行判断，减少一次判断
                // todo 看到这里
                if (type == 2)
                {
                    // 这里采用的策略是边缘镜像，所以使用abs的方法后，可以使得q_定位在
                    // 原矩阵的内部，并且以镜像的方式进行填充
                    q_ = abs(q_);
                    q_ = (channels - 1) - abs(q_ - (channels - 1));
                }
                const Mat m = bottom_blob.channel(q_);
                if (elemsize == 1)
                    copy_make_border_image<signed char>(m, borderm, top, left, type, static_cast<signed char>(pad_value));
                if (elemsize == 2)
                    copy_make_border_image<unsigned short>(m, borderm, top, left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(pad_value) : float32_to_bfloat16(pad_value));
                if (elemsize == 4)
                    copy_make_border_image<float>(m, borderm, top, left, type, pad_value);
            }
        }
        return 0;
    }

    return 0;
}

int Padding::forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const
{
    const Mat& bottom_blob = bottom_blobs[0];
    const Mat& reference_blob = bottom_blobs[1];

    Mat& top_blob = top_blobs[0];

    int _top;
    int _bottom;
    int _left;
    int _right;
    int _front;
    int _behind;
    {
        const int* param_data = reference_blob;

        _top = param_data[0];
        _bottom = param_data[1];
        _left = param_data[2];
        _right = param_data[3];
        _front = param_data[4];
        _behind = param_data[5];
    }
    if (_top == 0 && _bottom == 0 && _left == 0 && _right == 0 && _front == 0 && _behind == 0)
    {
        top_blob = bottom_blob;
        return 0;
    }

    int w = bottom_blob.w;
    int h = bottom_blob.h;
    int channels = bottom_blob.c;
    int dims = bottom_blob.dims;
    size_t elemsize = bottom_blob.elemsize;

    int outw = w + _left + _right;

    if (dims == 1)
    {
        top_blob.create(outw, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        if (elemsize == 1)
            copy_make_border_image<signed char>(bottom_blob, top_blob, 0, _left, type, static_cast<signed char>(value));
        if (elemsize == 2)
            copy_make_border_image<unsigned short>(bottom_blob, top_blob, 0, _left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(value) : float32_to_bfloat16(value));
        if (elemsize == 4)
            copy_make_border_image<float>(bottom_blob, top_blob, 0, _left, type, value);

        return 0;
    }

    int outh = h + _top + _bottom;

    if (dims == 2)
    {
        top_blob.create(outw, outh, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        if (elemsize == 1)
            copy_make_border_image<signed char>(bottom_blob, top_blob, _top, _left, type, static_cast<signed char>(value));
        if (elemsize == 2)
            copy_make_border_image<unsigned short>(bottom_blob, top_blob, _top, _left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(value) : float32_to_bfloat16(value));
        if (elemsize == 4)
            copy_make_border_image<float>(bottom_blob, top_blob, _top, _left, type, value);

        return 0;
    }

    int outc = channels + _front + _behind;

    if (dims == 3)
    {
        top_blob.create(outw, outh, outc, elemsize, opt.blob_allocator);
        if (top_blob.empty())
            return -100;

        #pragma omp parallel for num_threads(opt.num_threads)
        for (int q = 0; q < outc; q++)
        {
            Mat borderm = top_blob.channel(q);

            float pad_value = per_channel_pad_data_size ? per_channel_pad_data[q] : value;
            //Channel padding
            if (((q < _front) || (q >= (channels + _front))) && type == 0)
            {
                if (elemsize == 1)
                {
                    borderm.fill(static_cast<signed char>(pad_value));
                }
                if (elemsize == 2)
                {
                    borderm.fill(support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(pad_value) : float32_to_bfloat16(pad_value));
                }
                if (elemsize == 4)
                {
                    borderm.fill(pad_value);
                }
            }
            else
            {
                int q_ = q - _front;
                //Clamp channel
                if (type == 1)
                {
                    q_ = q_ <= 0 ? 0 : q_;
                    q_ = q_ >= channels - 1 ? channels - 1 : q_;
                }
                if (type == 2)
                {
                    q_ = abs(q_);
                    q_ = (channels - 1) - abs(q_ - (channels - 1));
                }

                const Mat m = bottom_blob.channel(q_);
                if (elemsize == 1)
                    copy_make_border_image<signed char>(m, borderm, top, left, type, static_cast<signed char>(pad_value));
                if (elemsize == 2)
                    copy_make_border_image<unsigned short>(m, borderm, top, left, type, support_fp16_storage && opt.use_fp16_storage ? float32_to_float16(pad_value) : float32_to_bfloat16(pad_value));
                if (elemsize == 4)
                    copy_make_border_image<float>(m, borderm, top, left, type, pad_value);
            }
        }

        return 0;
    }

    return 0;
}

} // namespace ncnn
